package com.ezjie.ielts.module_word;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.ielts.R;
import com.ezjie.ielts.core.base.BaseFragmentActivity;
import com.ezjie.ielts.core.http.HttpRequestAbstractCallBack;
import com.ezjie.ielts.model.SixDate;
import com.ezjie.ielts.model.SixDateItem;
import com.ezjie.ielts.model.SixDateResponse;
import com.ezjie.ielts.task.AgendaTask;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.DateUtil;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.view.agenda.CircleView;
import com.ezjie.ielts.view.agenda.DateWidgetDayCell;
import com.ezjie.ielts.view.agenda.DateWidgetDayHeader;
import com.ezjie.ielts.view.agenda.DayStyle;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

/**
 * 单词日历界面
 * 
 * @author wangwenpeng
 *
 */
@ContentView(R.layout.layout_wordagenda)
public class WordAgendaActivity extends BaseFragmentActivity {

	@ViewInject(R.id.tv_topbar_title)
	private TextView tv_topbar_title;
	@ViewInject(R.id.iv_topbar_back)
	private ImageView iv_topbar_back;
	@ViewInject(R.id.ll_word_agenda)
	private LinearLayout lmainLayout;

	// 页面控件
	private ScrollView mainSLayout;
	private LinearLayout mainLayout;
	private TextView Top_Date;
	private TextView Top_Year;
	private Button btn_pre_month;
	private Button btn_next_month;
	private TextView arrange_text;
	private LinearLayout arrange_layout;
	private LinearLayout sixdate_layout;

	// 控件宽度
	private int Calendar_Width;
	private int Cell_Width;

	// 生成日历，外层容器
	private LinearLayout layContent = null;
	private ArrayList<DateWidgetDayCell> days = new ArrayList<DateWidgetDayCell>();

	// 数据源
	private ArrayList<String> Calendar_Source = null;
	private List<SixDate> sixLists = new ArrayList<SixDate>();
	private Hashtable<Integer, Integer> calendar_Hashtable = new Hashtable<Integer, Integer>();
	private Boolean[] flag = null;
	private Calendar startDate = null;
	private Calendar endDate = null;

	// 日期变量
	public static Calendar calStartDate = Calendar.getInstance();
	private Calendar calToday = Calendar.getInstance();
	private Calendar calCalendar = Calendar.getInstance();
	private Calendar calSelected = Calendar.getInstance();

	// 当前操作日期
	private int iMonthViewCurrentMonth = 0;
	private int iMonthViewCurrentYear = 0;
	private int iFirstDayOfWeek = Calendar.SUNDAY;

	private AgendaTask agendaTask;
	private Context mContext;

	// 月份
	private String[] months_en = { "JAN", "FEB", "MAR", "APR", "MAY", "JUNE", "JULY", "AUG", "SEPT", "OCT", "NOV",
			"DEC" };
	String UserName = "";
	int dayvalue = -1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		agendaTask = new AgendaTask(this);

		// 获得屏幕宽和高，并計算出屏幕寬度分七等份的大小
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		int screenWidth = display.getWidth();
		Calendar_Width = screenWidth;
		Cell_Width = Calendar_Width / 8 + 1;

		init();
		mContext = this;
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_WORDAGENDA);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_WORDAGENDA);
	}

	private void init() {

		tv_topbar_title.setText("学习日历");
		iv_topbar_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		mainSLayout = new ScrollView(this);
		mainSLayout.setBackgroundColor(Color.WHITE);
		mainLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.calendar_main, null);
		// 声明控件，并绑定事件
		Top_Date = (TextView) mainLayout.findViewById(R.id.Top_Date);
		Top_Year = (TextView) mainLayout.findViewById(R.id.Top_Year);
		btn_pre_month = (Button) mainLayout.findViewById(R.id.btn_pre_month);
		btn_next_month = (Button) mainLayout.findViewById(R.id.btn_next_month);
		// btn_pre_month.setOnClickListener(new Pre_MonthOnClickListener());
		btn_next_month.setOnClickListener(new Next_MonthOnClickListener());

		LayoutParams Param1 = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
		arrange_layout = createLayout(LinearLayout.VERTICAL);
		sixdate_layout = createLayout(LinearLayout.VERTICAL);
		sixdate_layout.setBackgroundColor(getResources().getColor(R.color.six_line));
		layContent = createLayout(LinearLayout.VERTICAL);
		arrange_text = new TextView(this);
		arrange_text.setBackgroundColor(getResources().getColor(R.color.six_line));
		arrange_text.setTextColor(Color.BLACK);
		arrange_text.setTextSize(15);
		arrange_text.setPadding(56, 30, 0, 30);
		arrange_text.setText("当日任务");
		// arrange_layout.addView(generateCalendarMain());
		arrange_layout.addView(layContent);
		arrange_layout.addView(arrange_text);
		arrange_layout.addView(sixdate_layout, Param1);
		mainLayout.addView(arrange_layout, Param1);
		mainSLayout.addView(mainLayout, Param1);
		lmainLayout.addView(mainSLayout, Param1);

		// 计算本月日历中的第一天(一般是上月的某天)，并更新日历
		calStartDate = getCalendarStartDate();
		DateWidgetDayCell daySelected = updateCalendar();
		if (daySelected != null)
			daySelected.requestFocus();

		calToday = GetTodayDate();
		startDate = GetStartDate();
		endDate = GetEndDate(startDate);

		// 网络获取数据
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
		agendaTask.getAgenda(formatter.format(startDate.getTime()), formatter.format(endDate.getTime()),
				DateUtil.getLocalTimeZone(), new HttpRequestAbstractCallBack(mContext,true) {
					@Override
					public void onStartCallBack() {
						super.onStartCallBack();
						AppUtil.showProgressDialog(mContext);
					}

					@Override
					public void onSuccessCallBack(String result) {
						super.onSuccessCallBack(result);
						LogUtils.d(result);
						AppUtil.dismissProgressDialog();
						try {
							SixDateResponse res = JSON.parseObject(result, SixDateResponse.class);
							if (res != null) {
								SixDateItem item = JSON.parseObject(res.getData(), SixDateItem.class);
								sixLists = item.getAgenda_list();
								updateCalendar();
								int day = GetNumFromDate(calToday, startDate);
								days.get(day).doItemClick();
							}
						} catch (Exception e) {
							LogUtils.d("json数据异常");
							LogUtils.exception(e);
						}
					}

					@Override
					public void onFailureCallBack(HttpException error, String msg) {
						super.onFailureCallBack(error, msg);
						AppUtil.dismissProgressDialog();
						LogUtils.e(msg);
					}
				});

	}

	// 加载sixdate布局
	private void addSixDateLayout(SixDate date) {
		LinearLayout.LayoutParams Param1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 100);
		sixdate_layout.removeAllViews();
		for (int i = 0; i < date.getList().size(); i++) {
			LinearLayout six_layout = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.sixdate_item, null);
			if (i % 2 == 0) {
				six_layout.setBackgroundColor(getResources().getColor(R.color.six_item));
			} else {
				six_layout.setBackgroundColor(getResources().getColor(R.color.six_line));
			}
			CircleView cView = (CircleView) six_layout.findViewById(R.id.sixdate_img);
			TextView tView = (TextView) six_layout.findViewById(R.id.sixdate_txt);
			if (date.getList().get(i).str.equals(SixDate.key2)) {
				cView.setColor(getResources().getColor(R.color.six_dgreen));
				tView.setText("有" + date.getList().get(i).i + "组单词需要进行第一轮复习");
			} else if (date.getList().get(i).str.equals(SixDate.key3)) {
				cView.setColor(getResources().getColor(R.color.six_lgreen));
				tView.setText("有" + date.getList().get(i).i + "组单词需要进行第二轮复习");
			} else if (date.getList().get(i).str.equals(SixDate.key4)) {
				cView.setColor(getResources().getColor(R.color.six_blue));
				tView.setText("有" + date.getList().get(i).i + "组单词需要进行第三轮复习");
			} else if (date.getList().get(i).str.equals(SixDate.key5)) {
				cView.setColor(getResources().getColor(R.color.six_purple));
				tView.setText("有" + date.getList().get(i).i + "组单词需要进行第四轮复习");
			} else if (date.getList().get(i).str.equals(SixDate.key6)) {
				cView.setColor(getResources().getColor(R.color.six_red));
				tView.setText("有" + date.getList().get(i).i + "组单词需要进行第五轮复习");
			} else if (date.getList().get(i).str.equals(SixDate.key7)) {
				cView.setColor(getResources().getColor(R.color.six_yellow));
				tView.setText("有" + date.getList().get(i).i + "组单词需要进行第六轮复习");
			}
			sixdate_layout.addView(six_layout, Param1);
		}
		sixdate_layout.invalidate();
	}

	// 加载sixdate无数据布局
	private void addNoDataLayout() {
		LinearLayout.LayoutParams Param1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 110);
		sixdate_layout.removeAllViews();
		TextView text = new TextView(this);
		text.setText("当日暂无待复习词组");
		text.setPadding(45, 0, 0, 0);
		text.setGravity(Gravity.CENTER_VERTICAL);
		text.setTextSize(16);
		text.setBackgroundColor(getResources().getColor(R.color.six_item));
		sixdate_layout.addView(text, Param1);
		sixdate_layout.invalidate();
	}

	protected String GetDateShortString(Calendar date) {
		String returnString = date.get(Calendar.YEAR) + "/";
		returnString += date.get(Calendar.MONTH) + 1 + "/";
		returnString += date.get(Calendar.DAY_OF_MONTH);
		return returnString;
	}

	private View createLineView() {
		View view = new View(this);
		view.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, 1));
		view.setBackgroundColor(getResources().getColor(R.color.six_line));
		return view;
	}

	// 生成布局
	private LinearLayout createLayout(int iOrientation) {
		LinearLayout lay = new LinearLayout(this);
		lay.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
		lay.setOrientation(iOrientation);
		return lay;
	}

	// 生成日历头部
	private View generateCalendarHeader() {
		LinearLayout layRow = createLayout(LinearLayout.HORIZONTAL);

		for (int iDay = 0; iDay < 7; iDay++) {
			DateWidgetDayHeader day = new DateWidgetDayHeader(this, Cell_Width, 35);

			final int iWeekDay = DayStyle.getWeekDay(iDay, iFirstDayOfWeek);
			day.setData(iWeekDay);
			layRow.addView(day);
		}

		return layRow;
	}

	// 生成日历主体
	private View generateCalendarMain() {
		LinearLayout.LayoutParams Param2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		Param2.leftMargin = Cell_Width / 2;
		Param2.rightMargin = Cell_Width / 2;

		layContent.removeAllViews();
		layContent.setBackgroundColor(Color.WHITE);
		layContent.addView(generateCalendarHeader(), Param2);
		layContent.addView(createLineView());
		days.clear();

		double allDays = calCalendar.getActualMaximum(Calendar.DATE)
				+ (calCalendar.get(Calendar.DAY_OF_WEEK) - iFirstDayOfWeek);

		double row = Math.ceil(allDays / 7);

		for (int iRow = 0; iRow < row; iRow++) {
			layContent.addView(generateCalendarRow(), Param2);
			layContent.addView(createLineView());
		}

		return layContent;
	}

	// 生成日历中的一行，仅画矩形
	private View generateCalendarRow() {
		LinearLayout layRow = createLayout(LinearLayout.HORIZONTAL);

		for (int iDay = 0; iDay < 7; iDay++) {
			DateWidgetDayCell dayCell = new DateWidgetDayCell(this, Cell_Width, Cell_Width * 3 / 2);
			dayCell.setItemClick(mOnDayCellClick);
			days.add(dayCell);
			layRow.addView(dayCell);
		}

		return layRow;
	}

	// 设置当天日期和被选中日期
	private Calendar getCalendarStartDate() {
		calToday.setTimeInMillis(System.currentTimeMillis());
		calToday.setFirstDayOfWeek(iFirstDayOfWeek);

		if (calSelected.getTimeInMillis() == 0) {
			calStartDate.setTimeInMillis(System.currentTimeMillis());
			calStartDate.setFirstDayOfWeek(iFirstDayOfWeek);
		} else {
			calStartDate.setTimeInMillis(calSelected.getTimeInMillis());
			calStartDate.setFirstDayOfWeek(iFirstDayOfWeek);
		}

		UpdateStartDateForMonth();
		return calStartDate;
	}

	// 由于本日历上的日期都是从周日开始的，此方法可推算出上月在本月日历中显示的天数
	private void UpdateStartDateForMonth() {
		iMonthViewCurrentMonth = calStartDate.get(Calendar.MONTH);
		iMonthViewCurrentYear = calStartDate.get(Calendar.YEAR);
		calStartDate.set(Calendar.DAY_OF_MONTH, 1);
		calStartDate.set(Calendar.HOUR_OF_DAY, 0);
		calStartDate.set(Calendar.MINUTE, 0);
		calStartDate.set(Calendar.SECOND, 0);
		// update days for week
		UpdateCurrentMonthDisplay();
	}

	// 更新日历
	private DateWidgetDayCell updateCalendar() {
		DateWidgetDayCell daySelected = null;
		boolean bSelected = false;
		final boolean bIsSelection = (calSelected.getTimeInMillis() != 0);
		final int iSelectedYear = calSelected.get(Calendar.YEAR);
		final int iSelectedMonth = calSelected.get(Calendar.MONTH);
		final int iSelectedDay = calSelected.get(Calendar.DAY_OF_MONTH);
		calCalendar.setTimeInMillis(calStartDate.getTimeInMillis());

		if (calCalendar.get(Calendar.MONTH) == calToday.get(Calendar.MONTH)
				&& calCalendar.get(Calendar.YEAR) == calToday.get(Calendar.YEAR)) {
			btn_pre_month.setBackgroundDrawable(getResources().getDrawable(R.drawable.previous_month_not));
			btn_pre_month.setOnClickListener(null);
		} else {
			btn_pre_month.setBackgroundDrawable(getResources().getDrawable(R.drawable.previous_month));
			btn_pre_month.setOnClickListener(new Pre_MonthOnClickListener());
		}

		int beginDay = calCalendar.get(Calendar.DAY_OF_WEEK) - iFirstDayOfWeek;

		generateCalendarMain();

		for (int i = 0; i < days.size(); i++) {
			final int iYear = calCalendar.get(Calendar.YEAR);
			final int iMonth = calCalendar.get(Calendar.MONTH);
			final int iDay = calCalendar.get(Calendar.DAY_OF_MONTH);
			final int iDayOfWeek = calCalendar.get(Calendar.DAY_OF_WEEK);

			DateWidgetDayCell dayCell = days.get(i);

			// 清除开始天数之前的数据
			if (i < beginDay) {
				dayCell.clearData();
				continue;
			}

			// 清除最后一天数之后的数据
			if (iMonth != iMonthViewCurrentMonth) {
				dayCell.clearData();
				continue;
			}

			// 判断是否当天
			boolean bToday = false;
			boolean bYesterday = false;

			if (calToday.get(Calendar.YEAR) == iYear) {
				if (calToday.get(Calendar.MONTH) == iMonth) {
					if (calToday.get(Calendar.DAY_OF_MONTH) == iDay) {
						bToday = true;
					} else if (calToday.get(Calendar.DAY_OF_MONTH) > iDay) {
						bYesterday = true;
					}
				}
			}

			// check holiday
			boolean bHoliday = false;
			if ((iDayOfWeek == Calendar.SATURDAY) || (iDayOfWeek == Calendar.SUNDAY))
				bHoliday = true;
			if ((iMonth == Calendar.JANUARY) && (iDay == 1))
				bHoliday = true;

			// 是否被选中
			bSelected = false;

			if (bIsSelection)
				if ((iSelectedDay == iDay) && (iSelectedMonth == iMonth) && (iSelectedYear == iYear)) {
					bSelected = true;
				}

			dayCell.setSelected(bSelected);

			// 是否有记录
			boolean hasRecord = false;

			if (flag != null && flag[i] == true && calendar_Hashtable != null && calendar_Hashtable.containsKey(i)) {
				hasRecord = Calendar_Source.get(calendar_Hashtable.get(i)).contains(UserName);
			}

			if (bSelected)
				daySelected = dayCell;

			dayCell.setData(iYear, iMonth, iDay, bToday, bHoliday, iMonthViewCurrentMonth, hasRecord, bYesterday,
					sixLists);

			calCalendar.add(Calendar.DAY_OF_MONTH, 1);
		}

		layContent.invalidate();

		return daySelected;
	}

	// 更新日历标题上显示的年月
	private void UpdateCurrentMonthDisplay() {
		Top_Date.setText(months_en[calStartDate.get(Calendar.MONTH)]);
		Top_Year.setText(calStartDate.get(Calendar.YEAR) + "");
	}

	// 点击上月按钮，触发事件
	class Pre_MonthOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			MobclickAgent.onEvent(mContext, "word_study_month_change");
			// TODO Auto-generated method stub
			calSelected.setTimeInMillis(0);
			iMonthViewCurrentMonth--;

			if (iMonthViewCurrentMonth == -1) {
				iMonthViewCurrentMonth = 11;
				iMonthViewCurrentYear--;
			}

			calStartDate.set(Calendar.DAY_OF_MONTH, 1);
			calStartDate.set(Calendar.MONTH, iMonthViewCurrentMonth);
			calStartDate.set(Calendar.YEAR, iMonthViewCurrentYear);
			calStartDate.set(Calendar.HOUR_OF_DAY, 0);
			calStartDate.set(Calendar.MINUTE, 0);
			calStartDate.set(Calendar.SECOND, 0);
			calStartDate.set(Calendar.MILLISECOND, 0);
			UpdateStartDateForMonth();

			updateCalendar();
		}

	}

	// 点击下月按钮，触发事件
	class Next_MonthOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			MobclickAgent.onEvent(mContext, "word_study_month_change");
			calSelected.setTimeInMillis(0);
			iMonthViewCurrentMonth++;

			if (iMonthViewCurrentMonth == 12) {
				iMonthViewCurrentMonth = 0;
				iMonthViewCurrentYear++;
			}

			calStartDate.set(Calendar.DAY_OF_MONTH, 1);
			calStartDate.set(Calendar.MONTH, iMonthViewCurrentMonth);
			calStartDate.set(Calendar.YEAR, iMonthViewCurrentYear);
			UpdateStartDateForMonth();

			updateCalendar();
		}
	}

	// 点击日历，触发事件
	private DateWidgetDayCell.OnItemClick mOnDayCellClick = new DateWidgetDayCell.OnItemClick() {
		public void OnClick(DateWidgetDayCell item) {
			MobclickAgent.onEvent(mContext, "word_study_date_change");
			calSelected.setTimeInMillis(item.getDate().getTimeInMillis());
			item.setSelected(true);
			if (sixLists != null) {
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				String iDateAll = formatter.format(item.getDate().getTime());
				for (int i = 0; i < sixLists.size(); i++) {
					String date = sixLists.get(i).getDate();
					if (iDateAll.equals(date)) {
						addSixDateLayout(sixLists.get(i));
						break;
					} else {
						addNoDataLayout();
					}
				}
			}
			updateCalendar();
		}
	};

	public Calendar GetTodayDate() {
		Calendar cal_Today = Calendar.getInstance();
		cal_Today.set(Calendar.HOUR_OF_DAY, 0);
		cal_Today.set(Calendar.MINUTE, 0);
		cal_Today.set(Calendar.SECOND, 0);
		cal_Today.setFirstDayOfWeek(iFirstDayOfWeek);
		return cal_Today;
	}

	// 得到当前日历中的第一天
	public Calendar GetStartDate() {
		Calendar cal_Now = Calendar.getInstance();
		cal_Now.set(Calendar.DAY_OF_MONTH, 1);
		cal_Now.set(Calendar.HOUR_OF_DAY, 0);
		cal_Now.set(Calendar.MINUTE, 0);
		cal_Now.set(Calendar.SECOND, 0);
		return cal_Now;
	}

	public Calendar GetEndDate(Calendar startDate) {
		Calendar endDate = Calendar.getInstance();
		endDate = (Calendar) startDate.clone();
		endDate.add(Calendar.MONTH, 1);
		endDate.add(Calendar.DAY_OF_MONTH, -1);
		return endDate;
	}

	// 得到当天在日历中的序号
	private int GetNumFromDate(Calendar now, Calendar returnDate) {
		Calendar cNow = (Calendar) now.clone();
		Calendar cReturnDate = (Calendar) returnDate.clone();
		setTimeToMidnight(cNow);
		setTimeToMidnight(cReturnDate);

		long todayMs = cNow.getTimeInMillis();
		long returnMs = cReturnDate.getTimeInMillis();
		long intervalMs = todayMs - returnMs;
		int index = millisecondsToDays(intervalMs) + (cReturnDate.get(Calendar.DAY_OF_WEEK) - iFirstDayOfWeek);
		return index;
	}

	private int millisecondsToDays(long intervalMs) {
		return Math.round((intervalMs / (1000 * 86400)));
	}

	private void setTimeToMidnight(Calendar calendar) {
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
	}

	@Override
	public void onClickEvent(View view) {
		// TODO Auto-generated method stub

	}

}
